package com.hzy.fivepalace.admin.service;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzy.fivepalace.common.consts.RedisKeyConsts;
import com.hzy.fivepalace.common.service.redis.RedisCache;
import com.hzy.fivepalace.common.type.VipTypeEnums;
import com.hzy.fivepalace.common.util.ResponseUtil;
import com.hzy.fivepalace.common.page.TableDataInfo;
import com.hzy.fivepalace.db.dao.DtsPointsDetailMapper;
import com.hzy.fivepalace.db.dao.DtsUserMapper;
import com.hzy.fivepalace.db.dao.ex.AppUserCommissionDetaiMapperEx;
import com.hzy.fivepalace.db.dao.ex.DtsUserMapperEx;
import com.hzy.fivepalace.db.domain.DtsPointsDetail;
import com.hzy.fivepalace.db.domain.DtsPointsDetailExample;
import com.hzy.fivepalace.db.domain.DtsUser;
import com.hzy.fivepalace.db.domain.DtsUserExample;
import com.hzy.fivepalace.db.vo.wx.WxUserCommissionDetailDto;
import com.hzy.fivepalace.db.vo.wx.WxUserTeamVo;
import jodd.util.StringUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信用户服务
 */
@Service
public class AdminWxUserService {

    @Resource
    private DtsUserMapper userMapper;

    @Resource
    private Redisson redisson;

    @Resource
    private RedisCache redisCache;

    @Resource
    private DtsUserMapperEx dtsUserMapperEx;

    @Resource
    private DtsPointsDetailMapper dtsPointsDetailMapper;

    @Resource
    private AppUserCommissionDetaiMapperEx userCommissionDetaiMapperEx;

    /**
     * 获取用户团队列表
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public TableDataInfo getUserTeamList(Integer page, Integer size,Integer userId) {
        if(null==userId){
            return TableDataInfo.errorDataTable("请选择用户");
        }
        Page p = PageHelper.startPage(page, size);
        List<WxUserTeamVo> list = dtsUserMapperEx.getUserTeamList(userId);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        } else {
            list.forEach(item -> {
                if(null!=item.getVipType()&&null== VipTypeEnums.getEnum(item.getVipType())){
                    item.setVipType(null);
                }
            });
        }
        return TableDataInfo.getDataTable(list, p.getTotal());
    }

    /**
     * 获取用户佣金明细列表
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public TableDataInfo getUserCommissionDetailList(Integer page, Integer size,Integer userId) {
        if(null==userId){
            return TableDataInfo.errorDataTable("请选择用户");
        }
        Page p = PageHelper.startPage(page, size);
        List<WxUserCommissionDetailDto> list=userCommissionDetaiMapperEx.getUserCommissionDetailList(userId);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return TableDataInfo.getDataTable(list,  p.getTotal());
    }

    /**
     * 获取用户积分明细列表
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public TableDataInfo getUserPointsDetailList(Integer page, Integer size,Integer userId) {
        if(null==userId){
            return TableDataInfo.errorDataTable("请选择用户");
        }
        DtsPointsDetailExample query=new DtsPointsDetailExample();
        query.setOrderByClause("add_time desc,id desc");
        query.createCriteria().andUserIdEqualTo(userId);
        Page p = PageHelper.startPage(page, size);
        List<DtsPointsDetail> list= dtsPointsDetailMapper.selectByExample(query);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }else{
            list.forEach(item->{
                //不返回相关用户id
                item.setUserId(null);
                item.setToUserId(null);
            });
        }
        return TableDataInfo.getDataTable(list, p.getTotal());
    }


    /**
     * 用户列表
     *
     * @param status
     * @param nickname
     * @param phone
     * @param page
     * @param size
     * @return
     */
    public TableDataInfo getUserList(Integer status, String nickname, String phone, Integer page, Integer size) {
        DtsUserExample example = new DtsUserExample();
        example.orderBy("add_time desc");
        DtsUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (null != status) {
            criteria.andStatusEqualTo(status.byteValue());
        }
        if (!StringUtil.isBlank(phone)) {
            criteria.andMobileEqualTo(phone);
        }
        if (!StringUtil.isBlank(nickname)) {
            criteria.andNicknameLike("%" + nickname + "%");
        }
        example.or(criteria);
        Page p = PageHelper.startPage(page, size, true);
        List<Map<String,Object>> resultList =new ArrayList<>();
        List<DtsUser> list = userMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(user -> {
                DtsUser reUser=userMapper.selectByPrimaryKey(user.getRecodeUserId());

                //敏感信息不显示
                user.setWeixinOpenid(null);
                Map<String,Object> userInfo= JSON.parseObject(JSON.toJSONString(user));
                userInfo.put("reUser",reUser);//推荐人信息
                userInfo.put("commission",user.getCommission());//当前可提现佣金
                userInfo.put("commissionSumCount",userCommissionDetaiMapperEx.getUserCommissionSumCount(user.getId()));//佣金总数
                userInfo.put("toDayCommissionSumCount",userCommissionDetaiMapperEx.getUserToDayCommissionSumCount(user.getId()));//今日佣金
                userInfo.put("dividend",userCommissionDetaiMapperEx.getUserDividendSumCount(user.getId()));//分红
                userInfo.put("managementAward",userCommissionDetaiMapperEx.getUserManagementAwardSumCount(user.getId()));//管理奖

                resultList.add(userInfo);
            });
        }
        return TableDataInfo.getDataTable(resultList, p.getTotal());
    }

    /**
     * 启用禁用
     *
     * @param userId
     * @param status
     * @return
     */
    public Object updateUserStatus(Integer userId, Integer status) {
        RLock lock = redisson.getLock("admin_updateUserStatus_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (status != 0 && status != 1) {
            lock.unlock();
            return ResponseUtil.fail("参数【status】错误");
        }
        DtsUser user = userMapper.selectByPrimaryKey(userId);
        if (null == user || user.getDeleted()) {
            lock.unlock();
            return ResponseUtil.fail("用户不存在或已被删除");
        }
        user.setStatus(status.byteValue());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateByPrimaryKeySelective(user);
        if (status == 1) {//如果当前操作为禁用，那就删除用户缓存
            String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userId)});
            redisCache.deleteObject(key);
        }
        lock.unlock();
        return ResponseUtil.ok(status == 1 ? "禁用成功" : "启用成功", null);
    }
}
